import { App } from 'vue';
import SvgIcon from '@/components/SvgIcon/index.vue';

export default {
  install(app: App) {
    app.component('SvgIcon', SvgIcon);
    // Dynamically build SVG sprite from raw SVG files
    const modules = import.meta.glob('./svg/*.svg', { as: 'raw', eager: true }) as Record<string, string>;
    const parser = new DOMParser();
    const sprite = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    sprite.setAttribute('aria-hidden', 'true');
    sprite.style.position = 'absolute';
    sprite.style.width = '0';
    sprite.style.height = '0';
    sprite.style.overflow = 'hidden';
    Object.entries(modules).forEach(([path, raw]) => {
      const doc = parser.parseFromString(raw, 'image/svg+xml');
      const svgEl = doc.querySelector('svg');
      if (!svgEl) return;
      const symbol = document.createElementNS('http://www.w3.org/2000/svg', 'symbol');
      const name = path.match(/\.\/svg\/(.+)\.svg$/)?.[1] || '';
      symbol.setAttribute('id', `icon-${name}`);
      const viewBox = svgEl.getAttribute('viewBox');
      if (viewBox) {
        symbol.setAttribute('viewBox', viewBox);
      }
      Array.from(svgEl.childNodes).forEach(node => {
        symbol.appendChild(node.cloneNode(true));
      });
      sprite.appendChild(symbol);
    });
    document.body.insertBefore(sprite, document.body.firstChild);
  }
};
